package rsj.util;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuanqinglong
 * @since 2021/3/12 15:08
 */
public class HumpToLineUtil {

    /**
     * 将驼峰的字段转首字母大写的蛇形
     *
     * @param key 字段
     * @return .
     */
    public static String toFirstUppercase(String key) {
        return getItemName(humpToLine(key));
    }


    public static String conversionField(String json) {
        List<Map> list = JSONArray.parseArray(json, Map.class);
        for (int i = 0; i < list.size(); i++) {
            Map map = list.get(i);
            Map<String, Object> element = new HashMap<>();
            map.forEach((key, v) -> element.put(getItemName(humpToLine((String) key)), v));
            list.set(i, element);
        }
        return JSONObject.toJSONString(list);
    }

    public static String getItemName(String dbKey) {
        if (dbKey != null && !"".equals(dbKey)) {
            dbKey = dbKey.toLowerCase();
            StringBuilder sb = new StringBuilder();
            char[] chars = dbKey.toCharArray();

            for (int i = 0; i < chars.length; ++i) {
                if (i == 0) {
                    sb.append(("" + chars[i]).toUpperCase());
                } else if (chars[i] == '_') {
                    ++i;
                    sb.append(("_" + chars[i]).toUpperCase());
                } else {
                    sb.append(chars[i]);
                }
            }

            return sb.toString();
        } else {
            return null;
        }
    }

    /**
     * 驼峰转下划线
     */

    public static String humpToLine(String str) {
        return str.replaceAll("[A-Z]", "_$0").toLowerCase();

    }
}
